/**
 The MIT License

Copyright (c) <2011> <JPACHUBE Team>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
package com.pachube.v1.impl;

import java.awt.Color;

import com.pachube.api.Feed;
import com.pachube.api.Pachube;
import com.pachube.api.Trigger;
import com.pachube.exceptions.PachubeException;
import com.pachube.http.client.HttpClient;
import com.pachube.http.client.HttpMethod;
import com.pachube.http.client.HttpRequest;
import com.pachube.http.client.HttpResponse;

/**
 * The Class PachubeV1Impl.
 */
public class PachubeV1Impl implements Pachube {

    /**
     * HttpClient which will send HttpRequests to <a href="http://pachube.com"
     * >Pachube</a>
     */
    private HttpClient client;

    /** API key for your user account on Pachube. */
    private String API_KEY;

    /**
     * Constructor.
     * 
     * @param APIKEY the aPIKEY
     */
    public PachubeV1Impl(String APIKEY) {
        this.API_KEY = APIKEY;
        this.client = new HttpClient("www.pachube.com");
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#getFeed(int)
     */
    public Feed getFeed(int feed) throws PachubeException {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/feeds/"
                + feed + ".xml");
        hr.setMethod(HttpMethod.GET);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        HttpResponse g = this.client.send(hr);

        if (g.getHeaderItem("Status").equals("HTTP/1.1 200 OK")) {
            return PachubeV1Utils.toFeed(this, g.getBody());
        } else {
            throw new PachubeException(g.getHeaderItem("Status"));
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#createFeed(Pachube.Feed)
     */
    public Feed createFeed(Feed f) throws PachubeException {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/feeds");
        hr.setMethod(HttpMethod.POST);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        hr.setBody(f.toXML());
        HttpResponse g = this.client.send(hr);

        if (g.getHeaderItem("Status").equals("HTTP/1.1 201 Created")) {

            String[] a = g.getHeaderItem("Location").split("/");
            Feed n = this.getFeed(Integer.parseInt(a[a.length - 1]));
            f = n;
            return n;
        } else {
            throw new PachubeException(g.getHeaderItem("Status"));
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#updateFeed(int, java.lang.String)
     */
    public boolean updateFeed(int feed, String s) throws PachubeException {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/feeds/"
                + feed + ".xml");
        hr.setMethod(HttpMethod.PUT);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        hr.setBody(s);
        HttpResponse g = this.client.send(hr);

        if (g.getHeaderItem("Status").equals("HTTP/1.1 200 OK")) {
            return true;
        } else {
            throw new PachubeException(g.getHeaderItem("Status"));
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#deleteFeed(int)
     */
    public HttpResponse deleteFeed(int feed) {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/feeds/"
                + feed);
        hr.setMethod(HttpMethod.DELETE);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        return this.client.send(hr);
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#createDatastream(int, java.lang.String)
     */
    public boolean createDatastream(int feed, String s) throws PachubeException {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/feeds/"
                + feed + "/datastreams/");
        hr.setMethod(HttpMethod.POST);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        hr.setBody(s);
        HttpResponse g = this.client.send(hr);

        if (g.getHeaderItem("Status").equals("HTTP/1.1 201 Created")) {
            return true;
        } else {
            throw new PachubeException(g.getHeaderItem("Status"));
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#deleteDatastream(int, int)
     */
    public HttpResponse deleteDatastream(int feed, int datastream) {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/feeds/"
                + feed + "/datastreams/" + datastream);
        hr.setMethod(HttpMethod.DELETE);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        return this.client.send(hr);
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#updateDatastream(int, int, java.lang.String)
     */
    public HttpResponse updateDatastream(int feed, int datastream, String s) {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/feeds/"
                + feed + "/datastreams/" + datastream);
        hr.setMethod(HttpMethod.PUT);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        hr.setBody(s);
        System.out.println(hr.getHttpCommand());
        return this.client.send(hr);
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#getDatastream(int, int)
     */
    public HttpResponse getDatastream(int feed, int datastream) {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/feeds/"
                + feed + "/datastreams/" + datastream + ".xml");
        hr.setMethod(HttpMethod.GET);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        return this.client.send(hr);
    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#getDatastreamHistory(int, int)
     */
    public Double[] getDatastreamHistory(int feed, int datastream) {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/feeds/" + feed
                + "/datastreams/" + datastream + "/history.csv");
        hr.setMethod(HttpMethod.GET);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        String str = this.client.send(hr).getBody();
        String[] arr = str.split(",");
        Double[] arr1 = new Double[arr.length];
        for (int i = 0; i < arr.length; i++) {
            arr1[i] = Double.parseDouble(arr[1]);
        }

        return arr1;

    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#getDatastreamArchive(int, int)
     */
    public String[] getDatastreamArchive(int feed, int datastream) {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/feeds/" + feed
                + "/datastreams/" + datastream + "/archive.csv");
        hr.setMethod(HttpMethod.GET);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        String str = this.client.send(hr).getBody();
        return str.split("\n");

    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#createTrigger(Pachube.Trigger)
     */
    public String createTrigger(Trigger t) throws PachubeException {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/triggers");
        hr.setMethod(HttpMethod.POST);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        hr.setBody(t.toString());
        HttpResponse h = this.client.send(hr);
        if (h.getHeaderItem("Status").equals("HTTP/1.1 201 Created")) {
            return h.getHeaderItem("Location");
        } else {
            throw new PachubeException(h.getHeaderItem("Status"));
        }

    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#getTrigger(int)
     */
    public Trigger getTrigger(int id) throws PachubeException {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/triggers/"
                + id + ".xml");
        hr.setMethod(HttpMethod.GET);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        HttpResponse h = this.client.send(hr);

        return PachubeV1Utils.toTrigger(h.getBody())[0];

    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#getTriggers()
     */
    public Trigger[] getTriggers() throws PachubeException {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/triggers/");
        hr.setMethod(HttpMethod.GET);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        HttpResponse h = this.client.send(hr);

        return PachubeV1Utils.toTrigger(h.getBody());

    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#deleteTrigger(int)
     */
    public HttpResponse deleteTrigger(int id) {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/triggers/"
                + id);
        hr.setMethod(HttpMethod.DELETE);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        return this.client.send(hr);

    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#updateTrigger(int, Pachube.Trigger)
     */
    public HttpResponse updateTrigger(int id, Trigger t) {
        HttpRequest hr = new HttpRequest("http://www.pachube.com/api/triggers/"
                + id);
        hr.setMethod(HttpMethod.PUT);
        hr.addHeaderItem("X-PachubeApiKey", this.API_KEY);
        hr.setBody(t.toString());
        return this.client.send(hr);

    }

    /*
     * (non-Javadoc)
     * 
     * @see Pachube.Pachube#showGraph(int, int, int, int, java.awt.Color)
     */
    public String showGraph(int feedID, int streamID, int width, int height,
            Color c) {
        String hexRed = Integer.toHexString(c.getRed()).toString();
        String hexGreen = Integer.toHexString(c.getGreen()).toString();
        String hexBlue = Integer.toHexString(c.getBlue()).toString();
        if (hexRed.length() == 1) {
            hexRed = "0" + hexRed;
        }

        if (hexGreen.length() == 1) {
            hexGreen = "0" + hexGreen;
        }
        if (hexBlue.length() == 1) {
            hexBlue = "0" + hexBlue;
        }
        String hex = (hexRed + hexGreen + hexBlue).toUpperCase();

        return "http://www.pachube.com/feeds/" + feedID + "/datastreams/"
                + streamID + "/history.png?w=" + width + "&h=" + height + "&c="
                + hex;

    }

}
